Lambda is an operator used to denote anonymous functions or closures, following the usage of lambda calculus, in programming languages such as C#, Erlang, Lisp, Python, Ruby, Scala, and recently C++11, the latest iteration of C++.
Contents |
In C#, lambda expressions are often used with LINQ:
var allWikipediaPages = GetAllWikipediaPages(); var lambdaWikipediaPage = allWikipediaPages.First(wp => wp.Title == "Lambda (programming)");
In C++, lambda expressions can take this form:
auto square = [] (int x) -> int { return x * x; }; square(5); // returns 25
In Erlang, lambda expressions (usually called as "funs") can take this form:
F = fun(X) -> X * X end, F(5). % returns 25
In Haskell, lambda expressions can take this form:
Prelude> let f = \x -> x + 1 Prelude> :t f f :: Integer -> Integer Prelude> f 2 3
In Python, an example of this use of lambda is this sample of computer code that sorts a list alphabetically by the last character of each entry:
>>> stuff = ['woman', 'man', 'horse', 'boat', 'plane', 'dog'] >>> sorted(stuff, key=lambda word: word[-1]) ['horse', 'plane', 'dog', 'woman', 'man', 'boat']
In Scala, lambda expressions can take this form:
scala> (x:Int, y:Int) => x + y res0: (Int, Int) => Int = <function2> scala> res0(1, 2) res1: Int = 3
Argument types can be inferred when applied to a list:
scala> List(1, 2, 3, 4) res0: List[Int] = List(1, 2, 3, 4) scala> res0.foldLeft(0)((x, y) => x + y) res1: Int = 10